#pragma once
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <memory>
#include "Log.hpp"
#include "InetAddr.hpp"
#include "Common.hpp"

// 封装socket，采用模版方法的设计模式
namespace SocketModule
{
    using namespace LogModule;
    using namespace InetAddrModule;
    const static int gbacklog = 16;

    // 基类socket,大部分方法都是纯虚函数
    class Socket
    {
    public:
        virtual ~Socket() {};
        virtual void SocketOrDie() = 0;
        virtual void BindOrDie(uint16_t port) = 0;
        virtual void ListenOrDie(int backlog) = 0;
        virtual int Accept(InetAddr *client) = 0;
        virtual void Close() = 0;
        virtual int Recv(std::string *out) = 0;
        virtual int Send(const std::string &message) = 0;
        virtual int Connect(const std::string &server_ip, uint16_t port) = 0;
        virtual int Fd() = 0;

    public:
        void BuildTcpSocketMethod(uint16_t port, int backlog = gbacklog)
        {
            SocketOrDie();
            BindOrDie(port);
            ListenOrDie(backlog);
        }
        void BuildTcpClientSocketMethod()
        {
            SocketOrDie();
        }
    };

    const static int defaultfd = -1;
    class TcpSocket : public Socket
    {
    public:
        TcpSocket() : _sockfd(defaultfd)
        {
        }

        TcpSocket(int fd) : _sockfd(fd)
        {
        }

        ~TcpSocket()
        {
        }

        virtual void SocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(LogLevel::FATAL) << "socket error";
                exit(SOCKET_ERR);
            }
            int opt = 1;
             setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); //设置端口号相同但ip地址不同的多个socket描述符
            LOG(LogLevel::INFO) << "socket success" << _sockfd;
        }

        virtual void BindOrDie(uint16_t port) override
        {
            InetAddr localaddr(port);
            int n = ::bind(_sockfd, localaddr.NetAddrPtr(), localaddr.NetAddrLen());
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "bind error";
                exit(BIND_ERR);
            }
            LOG(LogLevel::INFO) << "bind success";
        }

        virtual void ListenOrDie(int backlog) override
        {
            int n = ::listen(_sockfd, backlog);
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "listen error";
                exit(LISTEN_ERR);
            }
            LOG(LogLevel::INFO) << "listen success";
        }

        int Accept(InetAddr *client) override
        {
            struct sockaddr_in peer;                           // 客户端套接字地址
            socklen_t len = sizeof(peer);                      // 客户端套接字长度
            int connectfd = ::accept(_sockfd, CONV(peer), &len); // 输出型参数获取客户端套接字地址和地址长度
            if (connectfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept warning ...";
                return -1; // TODO
            }
            // client->SetAddr(peer);
            // return std::make_shared<TcpSocket>(connectfd);
            return connectfd;
        }

        virtual int Recv(std::string *out) override
        {
            char buffer[1024];
            ssize_t n = ::recv(_sockfd, buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = '\0';
                *out += buffer;
            }
            return n;
        }

         virtual int Send(const std::string &message) override
         {
            return ::send(_sockfd, message.c_str(), message.size(), 0);
         }

       virtual void Close() override
        {
            if (_sockfd >= 0)
            {
                ::close(_sockfd);
            }
        }

         virtual int Connect(const std::string &server_ip, uint16_t port) override
         {
            InetAddr server(server_ip, port);
            return ::connect(_sockfd, server.NetAddrPtr(), server.NetAddrLen());
         }

         virtual int Fd() override
         {
             return _sockfd;
         }

    private:
        int _sockfd;
    };
}